<?php

class ReclamoController extends AweController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    public $defaultAction = 'admin';

    public function filters() {
        return array(
            array('CrugeAccessControlFilter -error'),
        );
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if (Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->user->ui->loginUrl);
        }
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest) {
                echo $error['message'];
            } else {
                if ($error['code'] == 404) {
                    $this->layout = '//layouts/error';
                    $this->render('404', $error);
                } else if ($error['code'] == 401) {
                    $this->layout = '//layouts/error';
                    $this->render('401', $error);
                } else {
                    $this->render('error', $error);
                }
            }
        }
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $result = array();
        $result['success'] = true;
        $result['html'] = $this->renderPartial('_view', array('model' => $this->loadModel($id)), TRUE, TRUE);
        echo CJSON::encode($result);
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Reclamo;
        $model->estado = Reclamo_Constants::ESTADO_NO_LEIDO;
        $model->id_usuario_estudiante = Yii::app()->user->id;
        $model->fecha_creacion = Util::FechaActual();
        $model->calificacion = Reclamo_Constants::CALIFICACION_NO_CALIFICADO;
        $this->performAjaxValidation($model, 'reclamo-form');
        if (isset($_POST['Reclamo'])) {
            $model->attributes = $_POST['Reclamo'];
            if ($model->save()) {
                $this->redirect('adminEstudiante');
            }
        }
        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        $this->performAjaxValidation($model, 'reclamo-form');
        if (isset($_POST['Reclamo'])) {
            $model->attributes = $_POST['Reclamo'];
            if ($model->save()) {
                $this->actionAdmin();
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $userRol = Util::getRolUser(Yii::app()->user->id);
        if ($userRol == Constants::ROL_ESTUDIANTE) {
            $this->redirect('reclamos/reclamo/create');
        } else
        if ($userRol == Constants::ROL_ADMINISTRADOR || Yii::app()->user->isSuperAdmin) {
            $this->redirect('reclamos/reclamo/admin');
        }
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Reclamo('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Reclamo']))
            $model->attributes = $_GET['Reclamo'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * ADMIN DE ESTUDIANTES
     */
    public function actionAdminEstudiante() {
        $model = new Reclamo('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Reclamo'])) {
            $model->attributes = $_GET['Reclamo'];
        }
        $dp_estudiantes = $model->de_estudiante()->orden_estudiantes()->search();
        $this->render('admin_estudiantes', array(
            'dataProvider' => $dp_estudiantes,
        ));
    }

    /**
     * Historial de reclamos
     */
    public function actionHistorial() {
        $model = new Reclamo('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Reclamo'])) {
            $model->attributes = $_GET['Reclamo'];
            $model->fechas = $_GET['Reclamo']['fechas'] != '' ? $_GET['Reclamo']['fechas'] : null;
        }
        $dp_historial = $model->searchHistorial();
        $this->render('historial', array(
            'dataProvider' => $dp_historial,
        ));
    }

    public function actionAjaxResolver($id) {
        $result = array();
        $model = $this->loadModel($id);
        //marcar Revisado
        if ($model->estado != Reclamo_Constants::ESTADO_REVISADO) {
            Reclamo::model()->updateByPk($model->id, array('estado' => Reclamo_Constants::ESTADO_REVISADO));
        }
        //validacion
        if (isset($_POST['ajax']) && $_POST['ajax'] === '#reclamo-form') {
            $model->attributes = $_POST['Reclamo'];
            $result['success'] = $model->validate();
            $result['errors'] = $model->errors;
            if (!$result['success']) {
                echo json_encode($result);
                Yii::app()->end();
            }
        }
        if (isset($_POST['Reclamo'])) {
            $model->estado = Reclamo_Constants::ESTADO_RESUELTO;
            $model->fecha_resolucion = Util::FechaActual();
            $model->id_usuario_resolucion = Yii::app()->user->id;
            if ($model->save()) {
                $result['success'] = true;
                $result['data'] = $model->attributes;
            }
        } else {
            $result['success'] = true;
            $result['html'] = $this->renderPartial('_form_modal', array('model' => $model), true, true);
        }
        echo CJSON::encode($result);
    }

    public function actionAjaxCalificar($id) {
        $result = array();
        $model = $this->loadModel($id);
        //validacion
        if (isset($_POST['ajax']) && $_POST['ajax'] === '#reclamo-form') {
            $model->scenario = 'calificar';
            $model->attributes = $_POST['Reclamo'];
            $result['success'] = $model->validate();
            $result['errors'] = $model->errors;
            if (!$result['success']) {
                echo json_encode($result);
                Yii::app()->end();
            }
        }
        if (isset($_POST['Reclamo'])) {
            if ($model->calificacion != Reclamo_Constants::CALIFICACION_NO_CALIFICADO) {
                $model->estado = Reclamo_Constants::ESTADO_CALIFICADO;
                $model->fecha_calificacion = Util::FechaActual();
            }
            if ($model->save()) {
                $result['success'] = true;
                $result['data'] = $model->attributes;
            }
        } else {
            $result['success'] = true;
            $result['html'] = $this->renderPartial('_form_modal', array('model' => $model), true, true);
        }
        echo CJSON::encode($result);
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id, $modelClass = __CLASS__) {
        $model = Reclamo::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model, $form = null) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'reclamo-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
